<template>
  <j-modal
    :title="title"
    :width="width"
    v-if="visible"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('common.table.close')">
    <div>
     <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        <a-col :span="8">
          <!-- <a-form-item label="位置查询"> -->

            <a-form-model-item label="位置查询" prop="searchValue">
              <!-- <el-autocomplete
                v-model="state"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect"
                clearable
                ></el-autocomplete> -->

                <a-auto-complete
                  placeholder="请输入内容"
                  @search="handleSearch"
                  @select="handleSelect"
                  allowClear
                >
                <template slot="dataSource">
                  <a-select-option v-for="item in suggestions" :key="item.id" :title="item.title" :value="item.id">
                    {{ item.title }}
                  </a-select-option>
                </template>
              </a-auto-complete>
            </a-form-model-item>
          <!-- </a-form-item> -->
        </a-col>
      </a-row>
      </a-form>
      <div>位置：{{address||'请选择位置'}}</div>
      <div id="container" class="container"></div>
    </div>

  </j-modal>
</template>

<script>
import { debounce } from 'lodash'; // 或者你可以使用自己的防抖函数
export default {
  name: "TencentMap",
  components: {},
  props: {
    coordinate: {
      type: Object,
      default: () => {
        return {
          lat: '',
          lng: ''
        }
      }
    },
    visible: {
      type: Boolean ,
      default: false
    }
  },
  data() {
    return {
      title: '设置地点',
      width: 1000,
      markerLayer: {},
      markerId: 'marker',
      location: this.coordinate,
      address:'',
      keyword:'',
      map:'',
      json:null,

      state: '',
      timeout:  null,
      suggestions: [], // 存储搜索建议
    }
  },
  mounted(){
     this.getMyLocation()
  },
  watch:{
     state(to){
        console.log("state-watch:", to);
       const KEY = "524BZ-SPPK6-QB3S6-MTGEU-OGZJ2-QCFYT";//这里是你自己的开发者秘钥
        let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
        this.$jsonp(url, {
                key: KEY,
                keyword: this.state,
                output: "jsonp",
              })
                .then((res) => {
                  res.data.forEach((item) => {
                    item.value = item.title;//因为element的远程搜索只能识别value所以需要对返回的数据进行一下处理
                  });
                    this.restaurants = res.data;

                })
                .catch((err) => {
                  console.log(err);
                });
      //  this.initDictConfig()
     }
  },
  methods: {
    searchOptions(keyword){
        const KEY = "524BZ-SPPK6-QB3S6-MTGEU-OGZJ2-QCFYT";//这里是你自己的开发者秘钥
        let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
        this.$jsonp(url, {
          key: KEY,
          keyword: keyword,
          output: "jsonp",
        }).then((res) => {
          // res.data.forEach((item) => {
          //   item.value = item.title;//因为element的远程搜索只能识别value所以需要对返回的数据进行一下处理
          // });
          console.log("searchOptions:", res);
          this.suggestions = res.data;
        })
        .catch((err) => {
          console.log(err);
        });

    },
    getMyLocation() {
      const KEY = window._CONFIG['qqMapKey']
      let url = 'https://apis.map.qq.com/ws/location/v1/ip'
      this.$jsonp(url, {
        key: KEY,
        output: 'jsonp'
      }).then(json => {
        this.location.lat = json.result.location.lat;
        this.location.lng = json.result.location.lng;
        this.tbjjlkd()
        this.initMap()
      }).catch(error => {
        this.$message.error('定位失败')
      })
    },
    initMap() {
      this.visible=true
      let center = new TMap.LatLng(this.location.lat, this.location.lng)
      let map = new TMap.Map(document.getElementById('container'), {
        center: center,
        zoom: 17.2,   //设置地图缩放级别
        pitch: 0,  //设置俯仰角
        rotation: 0    //设置地图旋转角度
      });
      this.markerLayer = new TMap.MultiMarker({
        id: 'marker-layer',
        map: map,
      })
      map.on('click', (evt) => {
        this.location.lat = evt.latLng.lat
        this.location.lng = evt.latLng.lng
        this.tbjjlkd()
        this.markerLayer.remove(this.markerId) //移除旧的标记
        this.markerLayer.add({
          id: this.markerId,
          position: new TMap.LatLng(this.location.lat, this.location.lng)
        })
      })
      this.map=map
      if (this.location.lat) {
        this.markerLayer.add({
          id: this.markerId,
          position: new TMap.LatLng(this.location.lat, this.location.lng)
        })
      }
    },
    // querySearchAsync(queryString, cb) {
    //     var restaurants = this.restaurants;
    //     var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

    //     clearTimeout(this.timeout);
    //     this.timeout = setTimeout(() => {
    //       cb(results);
    //     }, 3000 * Math.random());
    //   },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSearch(value) {
      console.log("handleSearch-watch:", value);
      debounce(()=> {
        console.log("handleSearch-watch2:", value);
          this.searchOptions(value);
      }, 300)() // 延迟200毫秒

      // searchOptions(keyword)

      // clearTimeout(this.timeout);
      // console.log();
      // // 模拟异步搜索（这里我们使用 setTimeout 来模拟）
      // this.timeout = setTimeout(() => {
      //   console.log("restaurants:", this.restaurants);
      //   const results = value ? this.restaurants.filter(this.createStateFilter(value)) : [];
      //   this.suggestions = results; // 更新搜索建议
      // }, 300); // 假设搜索响应时间为 300ms
    },
    // createStateFilter(queryString) {
    //   return (restaurant) => {
    //     // 注意：这里假设 restaurant 对象有一个 value 属性，你可能需要根据实际情况调整
    //     // 如果 restaurant 对象没有 value 属性，你可能需要使用 restaurant.name 或其他属性
    //     return restaurant.value.toLowerCase().startsWith(queryString.toLowerCase());
    //   };
    // },
    // handleChange(value) {
    //   console.log('onChange', value);
    // },
    handleSelect(value) {
      console.log("handleSelect:", value);
      const address = this.suggestions.find(item=> item.id ==value);
      console.log("handleSelect:", address);
      this.location.lat = address.location.lat;
      this.location.lng = address.location.lng;

      this.map.panTo([this.location.lat, this.location.lng]);
      this.address=  address.address

    },
    handleCancel() {
      this.visible = false
    },
    tbjjlkd(){
      // https://apis.map.qq.com/ws/geocoder/v1/?location
      let url = 'https://apis.map.qq.com/ws/geocoder/v1/'
      this.$jsonp(url, {
        location:this.location.lat+','+this.location.lng,
        key:'524BZ-SPPK6-QB3S6-MTGEU-OGZJ2-QCFYT',
        output:'jsonp'

      }).then(json => {
        this.address=json.result.address
        this.json=json.result
        // this.location.lat = json.result.location.lat;
        // this.location.lng = json.result.location.lng;
        // this.initMap()
      }).catch(error => {
        this.$message.error('定位失败')
      })
    },
    handleOk() {
      // this.$emit('onSel', this.location)
      this.$emit('dblclick',this.json)

    },
    // searchQuery(){
    //   let url = 'https://apis.map.qq.com/uri/v1/search'
    //   this.$jsonp(url, {
    //     keyword:this.keyword,
    //     key:'524BZ-SPPK6-QB3S6-MTGEU-OGZJ2-QCFYT',
    //     output:'jsonp'

    //   }).then(json => {

    //     this.datasslist=json.data.data
    //     // this.location.lat = json.result.location.lat;
    //     // this.location.lng = json.result.location.lng;
    //     // this.initMap()
    //   }).catch(error => {
    //     this.$message.error('定位失败')
    //   })

    // },
    searchReset(){
       this.keyword=''
    },
    open(location) {
      if (location && JSON.stringify(location) != "{}") {
        this.location = location
      }
      this.visible = true
      this.$nextTick(() => {
        if (!this.location.lat) {
          this.getMyLocation()
        } else {
          // this.initMap()
        }
      })
    }
  }
}
</script>

<style scoped>
.container{
    height: 500px;
    width:100%;
}

</style>
